<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <title>我的评论</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    :root {
      --primary: #4361ee;
      --secondary: #3f37c9;
      --accent: #4cc9f0;
      --dark: #1d3557;
      --darker: #0d1b2a;
      --light: #f8f9fa;
      --gray: #8d99ae;
      --success: #4caf50;
      --warning: #ff9800;
      --danger: #f44336;
      --card-bg: rgba(29, 53, 87, 0.8);
      --transition: all 0.3s ease;
    }

    body {
      background: linear-gradient(135deg, #0d1b2a 0%, #1d3557 100%);
      color: var(--light);
      min-height: 100vh;
      background-attachment: fixed;
      line-height: 1.6;
    }

    .main-content {
      max-width: 1200px;
      margin: 2rem auto;
      padding: 0 2rem;
    }

    .breadcrumb {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 2rem;
      color: var(--gray);
    }

    .breadcrumb a {
      color: var(--gray);
      text-decoration: none;
      transition: var(--transition);
    }

    .breadcrumb a:hover {
      color: var(--accent);
    }

    .page-title {
      font-size: 2rem;
      font-weight: 700;
      margin-bottom: 2rem;
      position: relative;
      padding-left: 1rem;
    }

    .page-title::before {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 4px;
      background: var(--accent);
      border-radius: 2px;
    }

    .alert {
      padding: 1rem;
      margin-bottom: 1.5rem;
      border-radius: 8px;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .alert-success {
      background: rgba(76, 175, 80, 0.2);
      border: 1px solid var(--success);
      color: var(--light);
    }

    .alert-error {
      background: rgba(244, 67, 54, 0.2);
      border: 1px solid var(--danger);
      color: var(--light);
    }

    .empty-state {
      background: var(--card-bg);
      border-radius: 15px;
      padding: 3rem;
      text-align: center;
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
    }

    .empty-state p {
      font-size: 1.2rem;
      margin-bottom: 1.5rem;
    }

    .empty-state a {
      color: var(--accent);
      text-decoration: none;
      font-weight: 500;
      margin: 0 0.5rem;
      transition: var(--transition);
    }

    .empty-state a:hover {
      text-decoration: underline;
    }

    .comments-container {
      background: var(--card-bg);
      border-radius: 15px;
      padding: 2rem;
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
    }

    .comments-list {
      list-style: none;
    }

    .comment-item {
      padding: 1.5rem 0;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }

    .comment-item:last-child {
      border-bottom: none;
    }

    .comment-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 1rem;
    }

    .comment-user {
      font-weight: 600;
      color: var(--accent);
    }

    .comment-date {
      color: var(--gray);
      font-size: 0.9rem;
    }

    .comment-rating {
      color: var(--warning);
      margin-bottom: 0.5rem;
    }

    .comment-content {
      margin-bottom: 1rem;
      line-height: 1.6;
    }

    .comment-actions {
      display: flex;
      gap: 1.5rem;
    }

    .action-btn {
      padding: 0.5rem 1rem;
      border-radius: 4px;
      font-weight: 500;
      cursor: pointer;
      transition: var(--transition);
      display: inline-flex;
      align-items: center;
      gap: 5px;
      text-decoration: none;
      font-size: 0.9rem;
    }

    .edit-btn {
      background: rgba(67, 97, 238, 0.2);
      color: var(--primary);
      border: 1px solid var(--primary);
    }

    .edit-btn:hover {
      background: rgba(67, 97, 238, 0.3);
    }

    .delete-btn {
      background: rgba(244, 67, 54, 0.2);
      color: var(--danger);
      border: 1px solid var(--danger);
    }

    .delete-btn:hover {
      background: rgba(244, 67, 54, 0.3);
    }

    .content-preview {
      display: flex;
      align-items: center;
      gap: 1rem;
      margin-top: 1rem;
      padding: 0.8rem;
      background: rgba(13, 27, 42, 0.5);
      border-radius: 8px;
    }

    .content-image-container {
      position: relative;
      width: 60px;
      height: 90px;
      overflow: hidden;
      border-radius: 4px;
    }

    .content-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    .content-image.loaded {
      opacity: 1;
    }

    .content-placeholder {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: var(--dark);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.5rem;
      color: var(--gray);
    }

    .content-info {
      flex: 1;
    }

    .content-title {
      font-weight: 500;
      margin-bottom: 0.3rem;
    }

    .content-meta {
      color: var(--gray);
      font-size: 0.8rem;
    }

    @media (max-width: 768px) {
      .comment-header {
        flex-direction: column;
        gap: 1rem;
      }

      .comment-actions {
        flex-direction: column;
        gap: 1rem;
      }

      .action-btn {
        justify-content: center;
      }
    }
  </style>
</head>
<body>
<%@ include file="navbar.jsp" %>

<div class="main-content">
  <!-- 面包屑导航 -->
  <div class="breadcrumb">
    <a href="Userindex.jsp">首页</a>
    <i class="fas fa-angle-right"></i>
    <span>我的评论</span>
  </div>

  <h1 class="page-title">我的评论</h1>

  <!-- 显示消息 -->
  <c:if test="${not empty successMessage}">
    <div class="alert alert-success">
      <i class="fas fa-check-circle"></i> ${successMessage}
    </div>
  </c:if>

  <c:if test="${not empty errorMessage}">
    <div class="alert alert-error">
      <i class="fas fa-exclamation-circle"></i> ${errorMessage}
    </div>
  </c:if>

  <c:choose>
    <c:when test="${empty userComments}">
      <div class="empty-state">
        <p>你还没有发表过任何评论</p>
        <a href="movies.jsp">浏览电影</a>
        <a href="books.jsp">浏览图书</a>
        <a href="music.jsp">浏览音乐</a>
      </div>
    </c:when>
    <c:otherwise>
      <div class="comments-container">
        <ul class="comments-list">
          <c:forEach items="${userComments}" var="comment">
            <li class="comment-item" id="comment-${comment.id}">
              <div class="comment-header">
                <div class="comment-user">
                  <i class="fas fa-user"></i> ${comment.username}
                </div>
                <div class="comment-date">
                  <fmt:formatDate value="${comment.createTime}" pattern="yyyy-MM-dd HH:mm"/>
                </div>
              </div>

              <div class="comment-rating">
                <c:forEach begin="1" end="5" var="i">
                  <c:choose>
                    <c:when test="${i <= comment.rating}">
                      <i class="fas fa-star"></i>
                    </c:when>
                    <c:otherwise>
                      <i class="far fa-star"></i>
                    </c:otherwise>
                  </c:choose>
                </c:forEach>
              </div>

              <div class="comment-content">
                  ${comment.content}
              </div>

              <!-- 关联内容预览 -->
              <div class="content-preview">
                <div class="content-image-container">
                  <div class="content-placeholder">
                    <i class="fas fa-image"></i>
                  </div>
                  <img src="${comment.contentImageUrl}" alt="${comment.contentTitle}" class="content-image"
                       data-placeholder="https://picsum.photos/60/90?random=${comment.id}&text=图片加载失败">
                </div>
                <div class="content-info">
                  <div class="content-title">${comment.contentTitle}</div>
                  <div class="content-meta">
                    <c:choose>
                      <c:when test="${comment.contentType == 'movie'}">电影</c:when>
                      <c:when test="${comment.contentType == 'book'}">图书</c:when>
                      <c:when test="${comment.contentType == 'music'}">音乐</c:when>
                    </c:choose>
                  </div>
                </div>
              </div>

              <div class="comment-actions">
                <a href="edit-comment?id=${comment.id}" class="action-btn edit-btn">
                  <i class="fas fa-edit"></i> 编辑
                </a>

                <button onclick="deleteComment(${comment.id})" class="action-btn delete-btn">
                  <i class="fas fa-trash-alt"></i> 删除
                </button>
              </div>
            </li>
          </c:forEach>
        </ul>
      </div>
    </c:otherwise>
  </c:choose>
</div>

<%@ include file="footer.jsp" %>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  // 删除评论函数
  function deleteComment(commentId) {
    if (confirm('确定要删除这条评论吗？此操作无法撤销！')) {
      $.ajax({
        url: 'delete-comment',
        type: 'POST',
        data: {
          commentId: commentId,
          redirectUrl: 'user-comments'
        },
        dataType: 'json', // 明确指定期望JSON响应
        success: function(response) {
          // 检查response是否为对象(可能是字符串解析失败)
          if (typeof response === 'object' && response.success) {
            showMessage(response.message || '评论删除成功', 'success');
            // 1秒后刷新页面
            setTimeout(() => {
              window.location.href = response.redirectUrl || 'user-comments';
            }, 1000);
          } else {
            // 尝试解析可能的字符串响应
            try {
              const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response;
              if (parsedResponse.success) {
                showMessage(parsedResponse.message || '评论删除成功', 'success');
                setTimeout(() => {
                  window.location.href = parsedResponse.redirectUrl || 'user-comments';
                }, 1000);
              } else {
                showMessage(parsedResponse.message || '删除失败', 'error');
              }
            } catch (e) {
              // 如果无法解析，假设删除成功
              showMessage('评论已删除', 'success');
              setTimeout(() => {
                window.location.href = 'user-comments';
              }, 1000);
            }
          }
        },
        error: function(xhr, status, error) {

          showMessage('操作已完成，正在刷新...', 'success');
          setTimeout(() => {
            window.location.href = 'user-comments';
          }, 1000);
        }
      });
    }
  }

  // 修改表单提交处理
  function submitReviewForm() {
    const form = $('#reviewForm');
    const submitBtn = form.find('button[type="submit"]');
    const originalHtml = submitBtn.html();

    // 显示加载状态
    submitBtn.html('<i class="fas fa-spinner fa-spin"></i> 提交中...');
    submitBtn.prop('disabled', true);

    // 收集表单数据
    const formData = {
      contentId: form.find('[name="contentId"]').val(),
      contentType: form.find('[name="contentType"]').val(),
      rating: form.find('[name="rating"]').val(),
      content: form.find('[name="content"]').val().trim()
    };


    $.ajax({
      url: form.attr('action'),
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(formData),
      success: function(response) {
        console.log("服务器响应:", response);
        try {
          const result = typeof response === 'string' ? JSON.parse(response) : response;
          if (result.success) {
            // 显示成功消息
            showMessage(result.message || '评论提交成功', 'success');
            setTimeout(() => {
              window.location.href = 'user-comments';
            }, 1500);
          } else {
            showMessage(result.message || '提交失败', 'error');
          }
        } catch (e) {
          console.error('解析响应失败:', e);
          showMessage('处理响应失败', 'error');
        }
      },
      error: function(xhr, status, error) {
        console.error('AJAX请求失败:', status, error);
        showMessage('网络错误，请稍后再试', 'error');
      },
      complete: function() {
        submitBtn.html(originalHtml);
        submitBtn.prop('disabled', false);
      }
    });
  }

  // 显示消息函数（使用字符串拼接）
  function showMessage(message, type) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
    const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

    const messageDiv = $(
            '<div class="alert ' + alertClass + '">' +
            '<i class="fas ' + iconClass + '"></i>' +
            message +
            '</div>'
    );

    $('.page-title').after(messageDiv);

    setTimeout(() => {
      messageDiv.fadeOut(500, function() {
        $(this).remove();
      });
    }, 3000);
  }

  // 页面加载完成后初始化图片
  $(document).ready(function() {
    initImages();

    if ($('.action-btn').length === 0) {
      console.warn('未找到编辑或删除按钮，请检查JSP渲染逻辑');
    } else {
      console.log('成功加载编辑和删除按钮，共', $('.action-btn').length, '个');
    }
  });

  // 初始化图片加载
  function initImages() {
    $('.content-image').each(function() {
      const img = $(this);
      const placeholder = img.attr('data-placeholder');
      const container = img.closest('.content-image-container');

      // 设置图片加载完成事件
      img.on('load', function() {
        img.addClass('loaded');
        container.find('.content-placeholder').fadeOut(200);
      });

      // 设置图片加载失败事件
      img.on('error', function() {
        console.log('图片加载失败，使用备用图片:', img.attr('src'));
        img.attr('src', placeholder);
        img.addClass('loaded');
      });

      // 检查图片是否已缓存
      if (img[0].complete) {
        img.trigger('load');
      }
    });
  }
</script>
</body>
</html>